<?php

class jssdk
{
	private $appId = '';
	private $appSecret = '';

	public function __construct($param = 'wx_secret') {
		$rst = new sqlcon();
		$info = $rst->getInfo('value1, value2', 'param', "type = '" . $param . "'");
		if (!empty($info)) {
			$this->appId = $info['value1'];
			$this->appSecret = $info['value2'];
		}
	}

	public function getSignPackage() {
		$jsapiTicket = $this->getJsApiTicket();
		$timestamp = time();
		$nonceStr = $this->createNonceStr();

		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);
		$signPackage = array(
			"appId"     => $this->appId, 
			"nonceStr"  => $nonceStr, 
			"timestamp" => $timestamp, 
			"url"       => $url, 
			"signature" => $signature, 
			"rawString" => $string
		);
		return $signPackage;
	}

	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}

	private function getJsApiTicket() {
		$rst = new sqlcon();
		$ticket = '';

		//获取ticket的值与有效时间
		$data = $rst->getInfo('value1 as ticket, value2 as time', 'param', "type = 'wx_token'");
		
		if ($data['time'] < time()) {
			$accessToken = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
			$res = json_decode(util::httpGet($url));
			if (empty($res)) {
				return '';
			}
			$ticket = $res->ticket;
			if ($ticket) {
				$rst->addCollect('value1', $ticket);
				$rst->addCollect('value2', time() + 7000);
				$rst->addCollect('type', 'wx_token');
				$rst->updateInfo('param');
			}
		}
		else {
			$ticket = $data['ticket'];
		}

		return $ticket;
	}

	function getAccessToken($param = 'wx_token') {
		$rst = new sqlcon();
		$access_token = '';

		//获取token的值与有效时间
		$data = $rst->getInfo('value3 as token, value4 as time', 'param', "type = '" . $param . "'");

		if ($data['time'] < time()) {
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
			$res = json_decode(util::httpGet($url));
			if (empty($res)) {
				return '';
			}
			$access_token = $res->access_token;
			if ($access_token) {
				$rst->addCollect('value3', $access_token);
				$rst->addCollect('value4', time() + 7000);
				$rst->addCollect('type', $param);
				$rst->updateInfo('param');
			}
		}
		else {
			$access_token = $data['token'];
		}

		return $access_token;
	}
}